package com.pds.utils;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * excel模板下载
 */
public class ExcelTemplateUtil {

    /**
     * 下载static文件夹下的excel模板文件
     * @param response
     * @param templateFileName 模板文件名称
     * @param downloadFileName 保存文件名称
     */
    public static void downloadTemplate(HttpServletResponse response,String templateFileName,String downloadFileName){
        InputStream in = null;
        OutputStream outputStream =null;
        try {
            in = ExcelTemplateUtil.class.getClassLoader().getResourceAsStream("static/"+templateFileName);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(downloadFileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            XSSFWorkbook workBook  = new XSSFWorkbook(in);
            outputStream = response.getOutputStream();
            workBook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
